<template>
    <view class="page-box">
        <header class="header">
            <view class="top row verCenter">
                <view class="pic">
                    <image :src="info.logo" mode="aspectFill"></image>
                </view>
                <text class="text">{{ info.product_name }}</text>
            </view>
            <view class="info row avarage verCenter">
                <view class="left column rowCenter verCenter">
                    <text class="t1">{{ info.product_quota }}万</text>
                    <text class="t2">最高额度</text>
                </view>
                <view class="right column rowCenter verCenter">
                    <text class="t1">
                        {{ info.loan_cycle }}
                    </text>
                    <text class="t2">期数</text>
                </view>
            </view>
        </header>
        <view class="section">
            <view class="form-box">
                <view class="form-item">
                    <view class="title required">主贷人：</view>
                    <view class="input-box row">
                        <input type="text" placeholder="请输入主贷人姓名" placeholder-style="color: #6E767A;" class="uni-input" v-model="form.apply_name" />
                    </view>
                </view>
                <view class="form-item">
                    <view class="title required">手机号码：</view>
                    <view class="input-box">
                        <input type="number" inputmode="tel" placeholder="请输入主贷人本人手机号码" placeholder-style="color: #6E767A;" class="uni-input" v-model="form.apply_mobile" />
                    </view>
                </view>
                <view class="form-item">
                    <view class="title required">申请金额：</view>
                    <view class="input-box">
                        <input type="number" inputmode="decimal" placeholder="请输入申请金额" placeholder-style="color: #6E767A;" class="uni-input" v-model="form.apply_quota" />
                        <text class="text-bar">元</text>
                    </view>
                </view>
                <view class="form-item">
                    <view class="title required">所在城市：</view>
                    <view class="dropdown row bothSide verCenter" style="width: 100%;">
                        <view class="dropdown-wrap" style="width: 100%;">
                            <uni-data-picker :localdata="region" placeholder="请选择所在城市" popup-title="请选择城市" @change="onchange" @nodeclick="onnodeclick"></uni-data-picker>
                        </view>
                        <text class="dropdown-ico"></text>
                    </view>
                </view>
                <view class="form-item">
                    <view class="title required">图形验证码：</view>
                    <view class="input-code row bothSide verCenter">
                        <input type="text" placeholder="请输入图形验证码" placeholder-style="color: #6E767A;" class="uni-input" v-model="captcha_code" />
                        <view class="pic">
                            <image :src="captcha_code_url" mode="aspectFit" class="pic-code" @click="captcha"></image>
                        </view>
                    </view>
                </view>
                <view class="form-item">
                    <view class="title required">短信验证码：</view>
                    <view class="input-code row bothSide verCenter">
                        <input type="text" placeholder="请输入短信验证码" placeholder-style="color: #6E767A;" class="uni-input" v-model="form.code" maxlength="4" />
                        <button class="get-code row verCenter rowCenter" :class="{ isDisabled: isDisabled }" :disabled="isDisabled" @click="geyCode">{{ buttonText }}</button>
                    </view>
                </view>
                <view class="form-item" v-if="info.product_type == 2">
                    <view class="title required">表显里程：</view>
                    <view class="input-box row">
                        <input type="number" inputmode="decimal" placeholder="请输入车辆仪表盘显示的公里数" placeholder-style="color: #6E767A;" class="uni-input" v-model="form.mileage" />
                    </view>
                </view>
                <view class="form-item" v-if="info.product_type == 2">
                    <view class="title required">汽车行驶证(正面)：</view>
                    <view class="upload-list row verCenter">
                        <template v-if="image_list.length > 0">
                            <view class="pic-box" v-for="(v, index) in image_list" :key="index">
                                <image :src="v" mode="aspectFill" lazy-load="true" @click="previewChange(image_list, index)"></image>
                                <view class="delete row rowCenter verCenter" @click="deletePic(index)"><text class="iconfont icon-shanchu"></text></view>
                            </view>
                        </template>
                        <template v-if="info.product_type == 1">
                            <view class="default row rowCenter verCenter" @click="chooseImageChange()" v-if="image_list.length < maxNum"><text class="iconfont icon-a-juxing3"></text></view>
                        </template>
                        <template v-else-if="info.product_type == 2">
                            <view class="default row rowCenter verCenter" @click="chooseImageChangeYiXin()" v-if="image_list.length < maxNum"><text class="iconfont icon-a-juxing3"></text></view>
                        </template>
                        <view class="car-info column" v-if="plateNo && form.car_valuation">
                            <view class="car-text">车牌号：{{ plateNo }}</view>
                            <view class="car-text">您的爱车最高可贷金额：<text style="color: #f98119;">{{ (Number(form.car_valuation) * 1.2).toFixed(2) }}</text>万元</view>
                        </view>
                    </view>
                </view>
            </view>
            <view class="agreement row verCenter">
                <checkbox-group @change="checkboxChange">
                    <checkbox value="1" style="transform:scale(0.6)"></checkbox>
                </checkbox-group>
                <text class="t1">我已阅读并同意</text>
                <navigator class="tt" url="/pages/mine/agreement?type=1">《用户授权协议》</navigator>
                <navigator class="tt" url="/pages/mine/agreement?type=2">《个人信息隐私保护》</navigator>
            </view>
            <view class="btn row rowCenter verCenter" @click="submit()" :class="{ disabled: is_disabled }">提 交</view>
            <view class="prompt-text row rowCenter verCenter">*温馨提示：本次申请无任何费用，最终额度批复结果为准</view>
        </view>
        <!-- 提示弹窗 -->
        <uni-popup ref="popup" background-color="#ffffff" border-radius="30rpx" mask-background-color="rgba(0,0,0,0.7)" :mask-click="false">
            <view class="popup-content column rowCenter verCenter">
                <view class="content column">
                    <view class="title column rowCenter verCenter">
                        <text class="t1">融资申请合规确认 </text>
                    </view>
                    <view class="tt">尊敬的客户：</view>
                    <view class="desc-box">
                        <view class="desc">为保障你在本次贷款申请过程中的合法权益，避免因不合规操作影响贷款成功申请，请认真阅读并勾选确认以下内容：</view>
                        <view class="row" style="margin-bottom: 10rpx;">
                            <checkbox :checked="isConfirmed1" @click="onConfirmChange(1)" style="transform:scale(0.7)" />
                            <text style="color: red;">*</text>
                            <text>本次贷款为本人真实意愿申请，申请成功的贷款由本人使用，并非帮助他人申贷</text>
                        </view>
                        <view class="row" style="margin-bottom: 10rpx;">
                            <checkbox :checked="isConfirmed2" @click="onConfirmChange(2)" style="transform:scale(0.7)" />
                            <text style="color: red;">*</text>
                            <text>本次贷款在申请过程中，本人未被收取任何服务费、手续费、中介费等额外一切费用。</text>
                        </view>
                        <view class="info">如你在本次贷款中有发生上述现象，请立即终止本次申请，并向我司官方企微客服进行反馈</view>
                    </view>
                    <view class="confirm-btn row rowCenter verCenter" @click="riskStatement()">确认</view>
                </view>
            </view>
        </uni-popup>
    </view>
</template>

<script>
    import { API } from '@/util/api.js';
    import { setCookie, getCookie } from '@/util/util.js';
    import debounce from 'lodash/debounce';

    export default {
        data() {
            return {
                product_api: '',
                is_disabled: false, //二要素验证
                isConfirmed1: false,
                isConfirmed2: false,
                noexebshowFalg: true, //控制是否会触发生命周期
                defaultNum: '',
                info: {},
                isDisabled: false,
                buttonText: '获取验证码',
                countdown: 60,
                captcha_code: '',
                image_list: [], //图片列表
                maxNum: 1, //最大上传图片数量
                is_checked: false,
                region: [], //城市列表
                captcha_code_url: '',
                captcha_code_key: '',
                plateNo: '', //车牌
                form: {
                    channel_user_id: '', //渠道用户ID
                    product_id: '', //产品ID
                    apply_name: '', //申请人
                    apply_city: '', //申请城市
                    apply_quota: '', //申请额度
                    apply_mobile: '', //手机
                    code: '', //手机验证码
                    car_no: '', //车牌
                    mileage: '', //行驶里程
                    driving_license_original_img: '', //行驶证正本
                    car_valuation: '' //车辆估值
                }
            };
        },
        onLoad(options) {
            this.form.product_id = options.product_id;
            this.form.channel_user_id = options.channel_user_id;
            this.product_api = options.product_api || '';

            this.captcha();
            this.getRegion();
            this.getData();
            this.addScanQrcodeCount();
        },
        mounted() {
            let risk = getCookie('risk');

            if (risk !== '1') {
                this.open();
            }
        },
        methods: {
            /**
             * 监听城市
             * @param {Object} e
             */
            onchange(e) {

            },
            /**
             * 选择城市
             * @param {Object} node
             */
            onnodeclick(node) {
                this.form.apply_city = node.value;
                console.log(node)
            },
            onConfirmChange(type) {
                if (type == 1) {
                    this.isConfirmed1 = !this.isConfirmed1;
                } else {
                    this.isConfirmed2 = !this.isConfirmed2;
                }
            },
            /**
             * checkbox监听
             * @param {Object} e
             */
            checkboxChange(e) {
                var values = e.detail.value;
                if (values[0] == 1) {
                    this.is_checked = true;
                } else {
                    this.is_checked = false;
                }
            },
            open() {
                this.$refs.popup.open('center');
            },
            close() {
                this.$refs.popup.close();
            },
            /**
             * 刷新验证码
             */
            captcha() {
                this.request(API.captchaApp, 'GET', {}, true).then(res => {
                    this.captcha_code_key = res.key;
                    this.captcha_code_url = res.img;
                    this.$forceUpdate();
                });
            },
            /**
             * 上传图片
             */
            chooseImageChange() {
                uni.chooseImage({
                    count: 1,
                    sizeType: ['original'],
                    sourceType: ['album', 'camera'],
                    success: chooseImageRes => {
                        console.log('选择图片成功：', chooseImageRes);

                        // 显示loading
                        uni.showLoading({
                            title: '上传中...'
                        });

                        // 获取选择的图片路径数组
                        const imagePath = chooseImageRes.tempFilePaths[0]; // 获取选中的图片路径

                        //上传到服务器
                        uni.uploadFile({
                            url: API.uploadImage,
                            filePath: imagePath,
                            name: 'file',
                            formData: {
                                'source': 'appUser'
                            },
                            success: uploadFileRes => {
                                console.log('服务器上传图片成功：', uploadFileRes);
                                uni.hideLoading();
                                let data = JSON.parse(uploadFileRes.data);
                                if (data.code === 0) {
                                    this.form.driving_license_original_img = data.data;
                                    this.image_list.push(data.data);
                                    this.$forceUpdate();
                                } else {
                                    uni.showToast({
                                        title: data.msg,
                                        icon: 'none'
                                    });
                                }
                            },
                            fail: () => {
                                uni.hideLoading();
                                uni.showToast({
                                    title: '上传图片失败',
                                    icon: 'none'
                                });
                            }
                        });
                    }
                });
            },

            /**
             * 上传图片易鑫
             */
            chooseImageChangeYiXin() {
                if (!this.form.apply_mobile) {
                    uni.showToast({
                        title: '请输入手机号码',
                        icon: 'none'
                    });
                    return false;
                }
                if (!this.captcha_code) {
                    uni.showToast({
                        title: '请输入图形验证码',
                        icon: 'none'
                    });
                    return false;
                }
                if (!this.form.code) {
                    uni.showToast({
                        title: '请输入短信验证码',
                        icon: 'none'
                    });
                    return false;
                }
                if (!this.form.mileage) {
                    uni.showToast({
                        title: '请输入行驶里程',
                        icon: 'none'
                    });
                    return false;
                }

                // 验证行驶里程必须是正整数
                if (!/^\d+$/.test(this.form.mileage.toString()) || parseInt(this.form.mileage) <= 0) {
                    uni.showToast({
                        title: '行驶里程必须是正整数',
                        icon: 'none'
                    });
                    return false;
                }

                uni.chooseImage({
                    count: 1,
                    sizeType: ['original'],
                    sourceType: ['album', 'camera'],
                    success: chooseImageRes => {
                        console.log('选择图片成功：', chooseImageRes);

                        // 显示loading
                        uni.showLoading({
                            title: '识别中行驶证中...'
                        });

                        // 获取选择的图片路径数组
                        const imagePath = chooseImageRes.tempFilePaths[0]; // 获取选中的图片路径

                        //上传到服务器
                        uni.uploadFile({
                            url: API.uploadImage,
                            filePath: imagePath,
                            name: 'file',
                            formData: {
                                'source': 'appUser',
                                'is_use_ocr': 1, //是否使用图片识别，0-否，1-是
                                'mileage': this.form.mileage, //里程数
                                'apply_mobile': this.form.apply_mobile, //申请手机号码
                                'code': this.form.code //手机验证码
                            },
                            success: uploadFileRes => {
                                console.log('服务器上传图片成功：', uploadFileRes);
                                uni.hideLoading();
                                let data = JSON.parse(uploadFileRes.data);
                                if (data.code === 0) {
                                    this.form.driving_license_original_img = data.data.file_url;
                                    this.image_list.push(data.data.file_url); //行驶证
                                    this.plateNo = data.data.plateNo; //车牌
                                    this.form.car_no = data.data.plateNo; //车牌
                                    this.form.car_valuation = data.data.car_price; //车辆估值
                                    this.$forceUpdate();
                                } else {
                                    uni.showToast({
                                        title: data.msg,
                                        icon: 'none'
                                    });
                                }
                            },
                            fail: () => {
                                uni.hideLoading();
                                uni.showToast({
                                    title: '上传图片失败',
                                    icon: 'none'
                                });
                            }
                        });
                    }
                });
            },
            /**
             * 预览图片
             * @param {Object} img
             * @param {Object} index
             */
            previewChange(img, index) {
                this.noexebshowFalg = false; //不允许再次触发onshow这个生命周期
                uni.previewImage({
                    current: index,
                    urls: img
                });
            },
            /**
             * 删除图片
             * @param {Object} index
             */
            deletePic(index) {
                this.image_list.splice(index, 1);
            },
            /**
             * 获取地址
             */
            getRegion() {
                this.request(API.getRegion, 'GET', {}, true).then(res => {
                    if (res.code === 0) {
                        this.region = res.data[0].children;
                    } else {
                        uni.showToast({
                            title: res.msg,
                            icon: 'none'
                        });
                    }
                });
            },
            /**
             * 二要素核验接口
             */
            twoElementsRecognition(name, mobile) {
                this.request(API.twoElementsRecognition, 'POST', { name: name, mobile: mobile }, true).then(res => {
                    if (res.code === 0) {
                        this.is_disabled = false;
                    } else {
                        this.is_disabled = true;
                        uni.showToast({
                            title: res.msg,
                            icon: 'none'
                        });
                    }
                });
            },
            /**
             * 扫码数量接口
             */
            addScanQrcodeCount() {
                this.request(API.addScanQrcodeCount, 'POST', { channel_user_id: this.form.channel_user_id }, true).then(res => {

                });
            },
            getData() {
                this.request(API.productDetail, 'GET', { id: this.form.product_id }, true).then(res => {
                    if (res.code === 0) {
                        this.info = res.data;
                        //设置标题
                        uni.setNavigationBarTitle({
                            title: res.data.product_name
                        })
                        this.info.product_quota = parseFloat((Number(this.info.product_quota) / 10000).toFixed(2));
                    } else {
                        uni.showToast({
                            title: res.msg,
                            icon: 'none'
                        });
                    }
                });
            },
            /**
             * 获取验证码
             */
            geyCode() {
                if (this.isDisabled) return;
                if (!this.form.apply_mobile) {
                    uni.showToast({
                        title: '请输入手机号码',
                        icon: 'none'
                    });
                    return false;
                }
                if (!this.captcha_code) {
                    uni.showToast({
                        title: '请输入图形验证码',
                        icon: 'none'
                    });
                    return false;
                }

                //发送手机验证码
                this.sendMsgCode((res) => {
                    if (res.code === 0) {
                        //接口成功之后开始倒计时
                        this.isDisabled = true;
                        this.buttonText = `重新获取${this.countdown}秒`;

                        const countdownInterval = setInterval(() => {
                            this.countdown--;
                            this.buttonText = `重新获取${this.countdown}秒`;

                            if (this.countdown === 0) {
                                clearInterval(countdownInterval);
                                this.isDisabled = false;
                                this.buttonText = '获取验证码';
                                this.countdown = 60; // 重置倒计时
                            }
                        }, 1000);
                    }
                });

            },
            /**
             * 发送手机验证码
             */
            sendMsgCode(callback) {
                this.request(API.sendMsgCode, 'POST', {
                    captcha_code: this.captcha_code,
                    mobile: this.form.apply_mobile,
                    captcha_code_key: this.captcha_code_key,
                    type: 3
                }, true).then(res => {
                    typeof callback == 'function' && callback(res);
                    if (res.code === 0) {
                        uni.showToast({
                            title: res.data.content,
                            icon: 'success'
                        });
                    } else {
                        this.captcha();
                        uni.showToast({
                            title: res.msg,
                            icon: 'none'
                        });
                    }
                });
            },
            /**
             * 风险提示
             */
            riskStatement() {
                if (!this.isConfirmed1) {
                    uni.showToast({
                        title: '请勾选确认',
                        icon: 'none'
                    });
                    return false;
                }
                if (!this.isConfirmed2) {
                    uni.showToast({
                        title: '请勾选确认',
                        icon: 'none'
                    });
                    return false;
                }
                //标记弹窗 频率一天一次
                setCookie('risk', 1, 365);

                this.close();
            },
            submit() {
                if (!this.form.apply_name) {
                    uni.showToast({
                        title: '请输入主贷人姓名',
                        icon: 'none',
                        duration: 5000
                    });
                    return false;
                }
                if (!this.form.apply_mobile) {
                    uni.showToast({
                        title: '请输入申请手机号码',
                        icon: 'none',
                        duration: 5000
                    });
                    return false;
                }
                if (!this.form.apply_quota) {
                    uni.showToast({
                        title: '请输入申请金额',
                        icon: 'none',
                        duration: 5000
                    });
                    return false;
                }
                if (!this.form.apply_city) {
                    uni.showToast({
                        title: '请选择城市',
                        icon: 'none',
                        duration: 5000
                    });
                    return false;
                }
                if (!this.form.code) {
                    uni.showToast({
                        title: '请输入短信验证码',
                        icon: 'none',
                        duration: 5000
                    });
                    return false;
                }
                if (!this.is_checked) {
                    uni.showToast({
                        title: '请确认已阅读并同意相关条款',
                        icon: 'none',
                        duration: 5000
                    });
                    return false;
                }
                this.request(API.orderAdd, 'POST', this.form, true).then(res => {
                    if (res.code === 0) {
                        var car_valuation = (Number(this.form.car_valuation) * 1.2).toFixed(2);
                        if (this.info.product_type == 1) {
                            //自有产品
                            uni.showToast({
                                title: '提交成功',
                                icon: 'success'
                            })
                            setTimeout(() => {
                                //跳转预审
                                uni.navigateTo({
                                    url: `/pages/order/preReviewAddInfo?order_id=${res.data.order_id}`
                                });
                            }, 2000)
                        } else if (this.info.product_type == 2) {
                            //第三方产品-易鑫
                            uni.navigateTo({
                                url: `/pages/order/success?car_valuation=${encodeURIComponent(car_valuation)}`
                            });
                        } else {
                            uni.navigateTo({
                                url: `/pages/order/success?car_valuation=${encodeURIComponent(car_valuation)}`
                            });
                        }
                    } else {
                        uni.showToast({
                            title: res.msg,
                            icon: 'none',
                            duration: 5000
                        });
                    }
                });
            }
        }
    };
</script>

<style scoped lang="scss">
    @import '@/assets/css/order/add.scss';
</style>
